package com.simulated.communication.networkprocessing;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * @Author Markburt
 * @Description :
 * @DATE: 2020/5/4
 * @TIME: 下午 06:37
 * @YEAR: 2020
 * @Version :
 **/
@Component
public class WebSocketServer {


    private NioEventLoopGroup mainGroup;
    private NioEventLoopGroup subGroup;
    private ServerBootstrap bootstrap;
    private ChannelFuture future;


    /***
     * 静态内部类声明
     */
    private static class SingletonWSSever{
        static final WebSocketServer instance = new WebSocketServer();
    }

    /**
     * 公开获取的静态方法
     * @return
     */
    public static WebSocketServer getInstance(){
        return SingletonWSSever.instance;
    }


    /***
     * 私有构造器
     */
    private WebSocketServer(){
        //两个线程组
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        //启动类
        bootstrap = new ServerBootstrap();
        //定义启动的线程组,channel和初始化器
        bootstrap.group(mainGroup,subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketSeverInitializer());
    }

    /**
     * 服务器开启
     */
    public void start(){
        this.future = bootstrap.bind(9999);
        System.err.println("Netty Websocket Server start ....");
    }
}
